const Post = require('../models/post');
const { validationResult } = require('express-validator');

const postController = {
    async create(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { content, image_url, video_url, location, hashtags } = req.body;

        try {
            const { post_id } = await Post.create({
                user_id: req.user.user_id,
                content,
                image_url,
                video_url,
                location,
                hashtags
            });
            res.status(201).json({ post_id });
        } catch (error) {
            next(error);
        }
    },

    async getById(req, res, next) {
        try {
            const post = await Post.findById(req.params.post_id);
            if (!post) {
                return res.status(404).json({ error: 'Post not found' });
            }
            res.json(post);
        } catch (error) {
            next(error);
        }
    },

    async getByUserId(req, res, next) {
        const { limit = 10, offset = 0 } = req.query;

        try {
            const posts = await Post.findByUserId(req.params.user_id, parseInt(limit), parseInt(offset));
            res.json(posts);
        } catch (error) {
            next(error);
        }
    }
};

module.exports = postController;